﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using UnityEngine;
using NinjaToolbox.SubComponentModule.Internal;

namespace NinjaToolbox.SubComponentModule
{
    public class SubComponentModelUserData : IUnionSerializable
    {
        List<KeyValuePair<string, object>> mUserDataList;


        public SubComponentModelUserData()
        {
            mUserDataList = new List<KeyValuePair<string, object>>();
        }

        public void AddUserData(string key, object value)
        {
            mUserDataList.Add(new KeyValuePair<string, object>(key, value));
        }

        public void RemoveUserData(string key)
        {
            mUserDataList.RemoveAll(m => m.Key == key);
        }

        public object GetUserData(string key)
        {
            return mUserDataList.Find(m => m.Key == key).Value;
        }

        void IUnionSerializable.Serialize(UnionSerializeWriter serializeWriter)
        {
            serializeWriter.Write(mUserDataList.Count);

            for (int i = 0, iMax = mUserDataList.Count; i < iMax; i++)
            {
                var item = mUserDataList[i];

                if (!(item.Value is IUnionSerializable))
                    throw new System.NotSupportedException("Not supported non IUnionSerializable interface object!");

                serializeWriter.Write(item.Key);
                serializeWriter.Write(item.Value.GetType().FullName);
                (item.Value as IUnionSerializable).Serialize(serializeWriter);
            }
        }

        void IUnionSerializable.Deserialize(UnionSerializeReader serializeReader)
        {
            var listCount = serializeReader.ReadInt();
            mUserDataList = new List<KeyValuePair<string, object>>();

            for (int i = 0, iMax = listCount; i < iMax; i++)
            {
                var key = serializeReader.ReadString();
                var typeName = serializeReader.ReadString();

                var item = new KeyValuePair<string, object>(key, Activator.CreateInstance(Type.GetType(typeName)));

                (item.Value as IUnionSerializable).Deserialize(serializeReader);

                mUserDataList.Add(item);
            }
        }
    }
}
